$(function () {
    loadMyImage();
    let $l_file_ipt = $(".file-input");
    let $img_up_btn = $(".upload-btn");
    $l_file_ipt.change(function () {
        let $file_list_div = $(".file-lists");
        $file_list_div.empty();
        let files = document.getElementsByClassName("file-input")[0].files;
        let len = files.length;
        if (0 < len && len <= 5) {
            $(".upload-btn-div").css("display", "block");
        } else {
            alert("一次最多上传五张图片");
            $(".upload-btn-div").css("display", "none");
            return;
        }
        for (let i = 0; i < len; i++) {
            let name = files[i].name;
            $file_list_div.append($("<span class='file-name'>").html(name).on("click", function () {
            }));
        }
    });
    $img_up_btn.click(function () {
        let files = document.getElementsByClassName("file-input")[0].files;
        let $file_list_div = $(".file-lists");
        let count = files.length;
        $img_up_btn.addClass("is-loading");
        $.each(files, function (index, obj) {
            let fd = new FormData();
            fd.append("file", obj);
            fd.append("filename", obj.name);
            $.ajax({
                url: "image/upload",
                type: "post",
                data: fd,
                cache: false,
                processData: false,
                contentType: false,
                success: function (data) {
                    if (data === "-1") {
                        alert("会话超时，请刷新后重试");
                    } else if (data === "0") {
                        alert("参数错误");
                    } else {
                        displayMessage("is-success", "成功", "图片【" + obj.name + "】上传成功", true);
                        let $col1 = $("#image-show-col1");
                        let $col2 = $("#image-show-col2");
                        let $col3 = $("#image-show-col3");
                        let photo = JSON.parse(data);
                        let $card = createImageCard(photo);
                        if (index % 3 === 0) {
                            $col1.prepend($card);
                        } else if (index % 3 === 1) {
                            $col2.prepend($card);
                        } else {
                            $col3.prepend($card);
                        }
                    }
                    if (index === count - 1) {
                        $file_list_div.empty();
                        $img_up_btn.removeClass("is-loading");
                        $(".upload-btn-div").css("display", "none");
                    }
                },
                error: function () {
                    displayMessage("is-danger", "错误", "图片【" + obj.name + "】上传失败", true);
                    $file_list_div.empty();
                    $img_up_btn.removeClass("is-loading");
                    $(".upload-btn-div").css("display", "none");
                }
            });
        });
    });
    $("#login-out").click(function () {
        loginOut();
    });
    // $("input:radio[name='water-mark-font-style']").change(function(){
    //     //遍历radio集
    //     $("input:radio[name='water-mark-font-style']").each(function(){
    //         //当前radio是否为选中状态
    //         // alert($(this).is(':checked'));
    //     });
    // });
});


function loginOut() {
    $.post("signOut", function () {
        window.location.reload();
    });
}

function displayMessage(type, title, content, addAndDisplay) {
    let id = getUUID();
    let $article = $("<article class='message is-small'>").attr("id", id);
    let $div1 = $("<div class='message-header'>");
    let $p = $("<p>").html(title);
    let $btn = $("<button class='delete' aria-label='delete'>");
    $btn.on("click", function () {
        removeEleById(id);
    });
    $div1.append($p);
    $div1.append($btn);
    let $div2 = $("<div class='message-body'>").html(content);
    $article.append($div1);
    $article.append($div2);
    $article.addClass(type);
    if (!addAndDisplay) {
        return $article;
    }
    $(".info-area").append($article);
}


function removeEleById(id) {
    $("#" + id).remove();
}

function loadMyImage() {
    $.ajax({
        url: "image/display",
        type: "get",
        dataType: "json",
        cache: false,
        contentType: false,
        success: function (data) {
            if (data === "-1") {
                alert("会话超时，请刷新页面");
            } else if (data === "-2") {
                alert("查询出错，请重试");
            } else {
                calTotalSize(data);
                let $col1 = $("#image-show-col1");
                let $col2 = $("#image-show-col2");
                let $col3 = $("#image-show-col3");
                for (let i in data) {
                    let $card = createImageCard(data[i]);
                    if (i % 3 === 0) {
                        $col1.append($card);
                    } else if (i % 3 === 1) {
                        if (parseInt(i) === 1) {
                            // $card.css("margin-top", "100px");
                        }
                        $col2.append($card);
                    } else {
                        $col3.append($card);
                    }
                }
            }
        }
    });
}

function createImageCard(imageObj) {
    console.log(imageObj.name);
    console.log(imageObj.storagePath);
    let cardId = getUUID();
    let imgId = getUUID();
    let $div0 = $("<div class='card'>").css("margin-bottom", "30px").attr("id", cardId);
    let $div1 = $("<div class='card-image'>");
    let $figure = $("<figure class='image is-4by3'>");
    let $img = $("<img style='cursor: pointer'>").attr("id", imgId);
    let imgPath = imageObj.storagePath;
    if (imageObj.hasWaterMark) {
        imgPath = imageObj.markStoragePath;
    }
    $img.attr("src", "img/" + imgPath);
    $img.on("click", function () {
        let $img1 = $("#img-modal");
        $("#img-modal-img").attr("src", "/img" + imgPath + "?token=" + new Date());
        $img1.addClass("is-active");
    });
    $figure.append($img);
    $div1.append($figure);
    let $div2 = $("<div class='card-content'>");
    let $div3 = $("<div class='content'>");
    let $p0 = $("<p>").html(imageObj.name).css("text-overflow", "ellipsis").css("overflow", "hidden").css("white-space", "nowrap");
    let $p1 = $("<p>").html("大小: " + formatSize(imageObj.size));
    let $p2 = $("<p>").html("日期: " + formatTime(imageObj.uploadDate));
    let $footer = $("<footer class='card-footer'>");
    let $footer_item_1 = $("<a class='card-footer-item'>").attr("href", "javascript:void(0);" + imageObj.id).html("详情");
    $footer_item_1.on("click", function () {
        showPhotoInfo(imageObj, cardId);
    });
    let $footer_item_2 = $("<a class='card-footer-item'>").html("重置");
    $footer_item_2.on("click", function () {
        resetPhoto(imageObj, imgId);
    });
    let $footer_item_3 = $("<a class='card-footer-item'>").html("加水印");
    $footer_item_3.off().on("click", function () {
        addWaterMark(imageObj, imgId);
    });
    $footer.append($footer_item_1);
    $footer.append($footer_item_2);
    $footer.append($footer_item_3);
    $div3.append($p0);
    $div3.append($p1);
    $div3.append($p2);
    $div2.append($div3);
    $div0.append($div1);
    $div0.append($div2);
    $div0.append($footer);
    $div0.on("click", function () {
    });
    return $div0;
}


function showPhotoInfo(imageObj, cardId) {
    let $infoModal = $("#info-modal");
    $(".info-title").html(imageObj.name);
    $(".info-name").html("图像名称: " + imageObj.name);
    $(".info-author").html("图像作者: " + imageObj.author);
    $(".info-size").html("图像大小: " + formatSize(imageObj.size));
    $(".info-upload-date").html("上传日期: " + formatTime(imageObj.uploadDate));
    $(".info-is-water-mark").html("是否水印: " + (imageObj.hasWaterMark ? "有" : "无"));
    $(".info-del").on("click", function () {
        dropPhoto(imageObj.id, imageObj.name, cardId);
    });
    $infoModal.addClass("is-active");

}

function dropPhoto(id, name, cardId) {
    $.get({
        url: "/image/drop",
        data: {
            id: id
        },
        success: function (result) {
            if (result === "1") {
                displayMessage("is-info", "成功", "图片【" + name + "】删除成功", true);
                removeEleById(cardId);
            } else if (result === "0") {
                displayMessage("is-warning", "失败", "图片【" + name + "】删除失败，身份验证失败", true);
            } else if (result === "-1") {
                displayMessage("is-warning", "失败", "会话超时，请刷新重试", true);
            }
            $("#info-modal").removeClass("is-active");
        }
    });
}

function resetPhoto(imageObj, imgId) {
    $.get({
        url: "/image/reset",
        data: {
            id: imageObj.id,
        },
        success: function (result) {
            if (result === "-1") {
                alert("会话超时，请刷新后重试");
            } else if (result === "0") {
                alert("操作失败，请稍后重试");
            } else {
                displayMessage("is-info", "成功", "图像【" + imageObj.name + "】重置成功", true);
                let photo = JSON.parse(result);
                let $img = $("#" + imgId);
                $img.attr("src", "img" + photo.storagePath);
                $img.on("click", function () {
                    let $img1 = $("#img-modal");
                    $("#img-modal-img").attr("src", "img" + photo.storagePath);
                    $img1.addClass("is-active");
                });
            }
        }
    })
}

function addWaterMark(imageObj, imgId) {
    let count = 0;
    let $modal = $("#water-mark-modal");
    $(".water-mark-title").html("为图像【" + imageObj.name + "】添加水印");
    let $ipt = $(".water-mark-input");
    $ipt.val("图像来源: " + imageObj.author);
    $modal.addClass("is-active");
    let $addBtn = $(".water-mark-add");
    $addBtn.on("click", function () {
        $addBtn.addClass("is-loading");
        let mark = $ipt.val();
        if (mark != null && mark !== "") {
            if (count < 1) {
                count = count + 1;
                $.post({
                    url: "/image/addWaterMark",
                    data: {
                        id: imageObj.id,
                        text: mark,
                        loc: $(".water-mark-loc-sel").get(0).selectedIndex,
                        col: $(".water-mark-color-sel").get(0).selectedIndex,
                        plain: $(".radio-normal-font").prop("checked"),
                    },
                    cache: false,
                    success: function (result) {
                        $addBtn.removeClass("is-loading");
                        $(".water-mark-cancel").click();
                        if (result === "-1") {
                            alert("会话超时，请刷新后重试");
                        } else if (result === "0") {
                            alert("操作失败，请稍后重试");
                        } else {
                            displayMessage("is-success", "成功", "图像【" + imageObj.name + "】水印添加成功", true);
                            let photo = JSON.parse(result);
                            let $img = $("#" + imgId);
                            $img.attr("src", "/img" + photo.markStoragePath + "?token=" + new Date());
                            $img.on("click", function () {
                                let $img1 = $("#img-modal");
                                $("#img-modal-img").attr("src", "/img" + photo.markStoragePath + "?token=" + new Date());
                                $img1.addClass("is-active");
                            });
                        }
                    }
                });
            }
        } else {
            alert("请输入水印内容");
        }
    });
}

function calTotalSize(data) {
    let list = eval(data);
    $(".have-upload-count").html("已上传: " + list.length + " 张");
    let totalBytes = 0;
    for (let i in data) {
        totalBytes += data[i].size;
    }
    $(".quota-have-used").html("已使用: " + formatSize(totalBytes));
}

function formatSize(byte) {
    let mb = byte / 1024 / 1024;
    if (parseInt(mb) === 0) {
        let kb = byte / 1024;
        return kb.toFixed(2) + "KB"
    }
    return mb.toFixed(2) + "MB";
}

function formatTime(timestamp) {
    let date = new Date(timestamp);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = date.getDate() + ' ';
    let h = date.getHours() + ': ';
    let m = date.getMinutes();
    return Y + M + D + h + m;
}

function getUUID() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "";
    return s.join("");
}

function getRandomNum(n, m) {
    return parseInt(Math.random() * (m - n + 1) + n, 10);
}